(function () {
    $.fixedAlert = function (type, text) {
        noty({type: type, text: text, timeout: 2000});
    }

    $('#forgot-form').formValidation({
        framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            tel: {
                validators: {
                    notEmpty: {message: '手机号码不能为空'},
                    regexp: {regexp: /^1[0-9]{10}$/, message: '手机号码不正确'}
                },
                onSuccess: function (e, data) {
                    $('#send-btn').addClass('bg-green-active');
                },
                onError: function () {
                    $('#send-btn').removeClass('bg-green-active');
                }
            },
            code: {
                validators: {
                    notEmpty: {message: '验证码不能为空'}
                }
            },
            password: {
                validators: {
                    notEmpty: {message: '密码不能为空'}
                }
            }
        }
    }).on('success.form.fv', function (e) {
        e.preventDefault();
        var $form = $(e.target), fv = $form.data('formValidation');

        $.post('/api/public/v1/user/forgot', $form.serialize(), function (result) {
            if (result.success) {
                location.href = '/admin';
            } else {
                $.fixedAlert('warning', result.message || '重置失败');
            }
            if (fv.getSubmitButton()) {
                fv.disableSubmitButtons(false);
            }
        }, 'json');
    });

    $('#send-btn').click(function () {
        var self = $(this);
        if (self.hasClass('bg-green-active')) {
            $.post('/api/public/v1/user/send_code', {
                type: 'forgot',
                tel: $('input[name="tel"]').val()
            }, function (result) {
                if (result.success) {
                    self.removeClass('bg-green-active');
                    self.html('60');
                    var timer = setInterval(function () {
                        var time = parseInt(self.html());
                        if (time) {
                            self.html(time - 1);
                        } else {
                            clearInterval(timer);
                            self.html('发送');
                            self.addClass('bg-green-active');
                        }
                    }, 1000);

                    $.fixedAlert('success', '验证码发送成功');
                } else {
                    $.fixedAlert('warning', result.message || '验证码发送失败');
                }
            }, 'json');
        }
    });
})();